# -*- coding:utf-8 -*-
"""
    生成报告
"""
import tempfile, os, datetime

def detect_danger_file():
    """危险文件检测"""
    if not g_dangerous_files:
        return True

    log(red("危险文件报告："))
    for file in g_dangerous_files:
        log(file)
    log(red("危险文件报告结束"))


def device_evaluate(log_r, option):
    ntime = datetime.datetime.now()
    reportfile = option.filename
    log_r.info(green("报告汇总:"))
    log_r.info(green("    报告生成时间: {}".format(ntime)))
    high_threat_rating, medium_threat_rating, low_threat_rating = 0, 0, 0

    # 评分
    if len(g_message_high):
        high_threat_rating   = calc_rate("h", len(g_message_high))

    if len(g_message_medium):
        medium_threat_rating = calc_rate("m", len(g_message_medium))

    if len(g_message_low):
        low_threat_rating    = calc_rate("l", len(g_message_low))

    rating_num = 100 - high_threat_rating - medium_threat_rating - low_threat_rating
    rating_num =round(max(rating_num, 0), 1)


    if 0 <= rating_num < 80:
        log_r.info("    安全评分：{} 分, 存在安全风险且风险较高，请关注风险项".format(red(rating_num)))
    elif rating_num <= 95:
        log_r.info("    安全评分：{} 分, 存在安全风险且风险较低，请关注风险项".format(red(rating_num)))
    elif 95 < rating_num:
        log_r.info("    安全评分：{} 分, 无安全风险。".format(green(rating_num)))
    else:
        log_r.info(red("    安全评分：{} 分, 存在安全风险且安全风险极高".format(rating_num)))

    count = g_monitoring_objects_num["count"]
    log_r.info("    检测对象数量: {}".format(count))
    threat_num = len(g_message_high) + len(g_message_medium)
    disk_num   = len(g_message_high) + len(g_message_medium) + len(g_message_low)
    no_risk_count = count - len(g_message_high) - len(g_message_medium) - len(g_message_low)
    log_r.info("    高风险{}项、中风险{}项、低风险{}项、未知风险{}项、无风险{}项".format(red(len(g_message_high)), red(len(g_message_medium)), green(len(g_message_low)), green(0), green(no_risk_count)))
    g_dev_evaluate["evaluate"] = rating_num

def dump_report():
    data = json.dumps({
            "evaluate": g_dev_evaluate["evaluate"],
            "risk" : {
                "high" : g_message_high,
                "medium" : g_message_medium,
                "low" : g_message_low,
                "filelist": g_dangerous_files,
            }
        }, ensure_ascii=False, indent=1)
    open("/tmp/evaluate.json", "w+").write(data)

def report(option):
    """生成报告"""
    reportfile_path = "/tmp/report.txt"
    if os.path.exists(option.dirname):
        reportfile_path = os.path.join(option.dirname, option.filename)
    g_anscan_filepath["report"] = reportfile_path
    log_r = init_log_report(reportfile_path)
    device_evaluate(log_r, option)
    # log("------------------详细报告----------------------------")
    log_r.info("详细检测结果：")

    if g_message_high:
        log_r.info(red("    高风险 {} 项:".format(len(g_message_high))))
    else:
        log_r.info(green("    高风险 {} 项:".format(len(g_message_high))))
    for desc, info in g_message_high:
        log_r.info("        {} {}".format(red(desc), info))

    if g_message_medium:
        log_r.info(red("    中风险 {} 项:".format(len(g_message_medium))))
    else:
        log_r.info(green("    中风险 {} 项:".format(len(g_message_medium))))
    for desc, info in g_message_medium:
        log_r.info("        {} {}".format(red(desc), info))

    if g_message_low:
        log_r.info(yellow("    低风险 {} 项:".format(len(g_message_low))))
    else:
        log_r.info(green("    低风险 {} 项:".format(len(g_message_low))))
    for desc, info in g_message_low:
        log_r.info("        {} {}".format(red(desc), info))
    log_r.info(green("报告已完成"))

# def alarm_for_not_online(option):
#     """提醒禁用联网检测"""
#     if option.noonline:
#         log(red("\n警告：联网检测已禁用，无法使用深度检测\n"))

def online_detect(option):
    """ 联网检测 """

    # if option.noonline:
    #     return alarm_for_not_online(option)

    detect_danger_file()

    md5_filepath = calculation_md5(g_dangerous_files)
    # 清空g_dangerous_files
    g_dangerous_files.clear()
    g_dangerous_files[os.path.realpath("/tmp/evaluate.json")] = 1
    g_dangerous_files[g_anscan_filepath["report"]] = 1
    # g_dangerous_files[g_anscan_filepath["anscanlog"]] = 1
    g_dangerous_files["/tmp/anscan.log"] = 1
    g_dangerous_files[md5_filepath] = 1
    devi_result = device_info()
    g_dangerous_files["/tmp/netstat"] = 1
    g_dangerous_files["/tmp/ps"] = 1
    g_dangerous_files["/tmp/cpu"] = 1
    g_dangerous_files["/tmp/mem"] = 1
    g_dangerous_files["/tmp/disk"] = 1
    fname = tar(g_dangerous_files)
